#ifndef __SIGNAL_PROCESSING_H__
#define __SIGNAL_PROCESSING_H__

#include <math.h>
#include <fftw3.h>
#include "Device.h"

using std::size_t;

struct ShiftFFT {
    const size_t size, channel;
    size_t not_ready;
    double *in, *out, *amplitude;
    fftw_plan plan;
    ShiftFFT(size_t size_, size_t channel_) : size(size_), channel(channel_), not_ready(size_-1) {
        in=(double*)fftw_malloc(sizeof(double)*size);
        out=(double*)fftw_malloc(sizeof(double)*2*(size/2+1));
        amplitude=(double*)fftw_malloc(sizeof(double)*(size/2+1));
        plan = fftw_plan_dft_r2c_1d(int(size), in, (fftw_complex*)out, FFTW_MEASURE); 
    }
    ~ShiftFFT() {
        fftw_destroy_plan(plan);
        fftw_free(in);
        fftw_free(out);
        fftw_free(amplitude);
    }

    void sampleReceived(device::Sample sample) {
        std::copy(in+1,in+size,in);
        in[size-1]=sample[channel];
        if(not_ready) { 
            --not_ready;
            return;
        }
        fftw_execute(plan);
        for(size_t ii=0; ii<size/2+1; ++ii) {
            amplitude[ii]=sqrt(out[2*ii]*out[2*ii] + out[2*ii+1]*out[2*ii+1]);
        }
    }
    void syncChanged(bool sync) {
        if(sync) return;
        not_ready=size-1;
    }
};

#endif
